package com.google.gwt.gwtpages.client.page.loader;

import java.util.HashMap;
import java.util.Iterator;

import com.google.gwt.gwtpages.client.message.exceptions.PageNotFoundException;
import com.google.gwt.gwtpages.client.page.LoadedPageContainer;
import com.google.gwt.gwtpages.client.page.Page;
import com.google.gwt.gwtpages.client.page.PageAttributes;

/**
 * Simple {@link PageLoader} implementation. {@link Page} instances are
 * registered for specific page tokens.
 * 
 * @author Joe Hudson
 */
public abstract class SimplePageLoader implements PageLoader {

	private HashMap<String, Page> pages = new HashMap<String, Page>();
	private HashMap<String, PageAttributes> metaData = new HashMap<String, PageAttributes>();

	/**
	 * Register the page implementation
	 * 
	 * @param pageToken
	 *            the page token
	 * @param page
	 *            the page implementation
	 * @return this for chaining
	 */
	public SimplePageLoader registerPage(String pageToken, Page page) {
		return registerPage(pageToken, page, null);
	}

	/**
	 * Register the page implementation
	 * 
	 * @param pageToken
	 *            the page token
	 * @param page
	 *            the page implementation
	 * @param metaData
	 *            the {@link PageAttributes}
	 * @return this for chaining
	 */
	public SimplePageLoader registerPage(String token, Page page,
			PageAttributes metaData) {
		pages.put(token, page);
		if (null != metaData)
			this.metaData.put(token, metaData);
		return this;
	}

	public boolean isValidPageToken(String token) {
		return (null != pages.get(token));
	}

	public Iterator<String> getValidPageTokens() {
		return pages.keySet().iterator();
	}
	
	public void getPage(String pageToken, PageLoadCallback pageHandler) {
		Page p = pages.get(pageToken);
		if (null != p) {
			pageHandler.onPageFound(new LoadedPageContainer(pageToken, p, metaData
					.get(pageToken), this));
		} else {
			pageHandler.onPageNotFound(pageToken);
		}
	}

	public PageAttributes getPageAttributes(String token) throws PageNotFoundException {
		return metaData.get(token);
	}
}